//2019240016 刘艺 大数据191 进程管理（2）
//信号量解决同步问题
#include <windows.h>
#include <process.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int number = 1;
HANDLE hSemaphore;  //定义信号量句柄

unsigned __stdcall ThreadProc1(void * pArguments){
    while (number < 10){
        WaitForSingleObject(hSemaphore, INFINITE); //(3)等待信号量
        if ( number<10){
            printf(" sub thread 1 :number = %d\n",number);
            ++number;
        } else{
            printf(" sub thread 1 :number = %d\n",number);
        }
        ReleaseSemaphore(hSemaphore, 1, NULL);  //(4)释放信号量
    }
    _endthreadex(0);
    return 0;
}

unsigned __stdcall ThreadProc2(void * pArguments){
    while (number < 10){
        WaitForSingleObject(hSemaphore, INFINITE); //(3)等待信号量
        if ( number<10){
            printf(" sub thread 2 :number = %d\n",number);
            ++number;
        } else{
            printf(" sub thread 2 :number = %d\n",number);
        }
        ReleaseSemaphore(hSemaphore, 1, NULL);  //(4)释放信号量
         }
    _endthreadex(0);
    return 0;
}

//完成！！

int main(){
    HANDLE hHandles[2];
    unsigned threadID[2];

    hSemaphore = CreateSemaphore(NULL, 1, 1, "sema");
    //(2) 创建信号量对象，同时设置初始信号值和最大信号值

    hHandles[0] = (HANDLE) _beginthreadex(NULL, 0,&ThreadProc1,
                                          NULL, 0, &threadID[0]);
    hHandles[1] = (HANDLE) _beginthreadex(NULL, 0,&ThreadProc2,
                                          NULL, 0, &threadID[1]);

    WaitForMultipleObjects( 2, hHandles, TRUE, INFINITE );
    printf("main thread : number = %d\n", number);

    CloseHandle(hHandles[0]);
    CloseHandle(hHandles[1]);
    CloseHandle(hSemaphore);

    getchar();
    return 0;

}
